package com.jh.microservice.rest;

import com.jh.microservice.rest.service.EchoService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.DefaultTransactionStatus;

/**
 * @author Administrator
 * @projectName newforward
 * @title
 * @package com.jh.microservice.rest
 * @description
 * @date 2019/8/14 23:54
 */
@ComponentScan(basePackages = "com.jh.microservice.rest")
@EnableTransactionManagement
public class TransatonalApplication {

    @Component(value = "myTransation")
    public static class MyTransactionManagement implements PlatformTransactionManager {
        @Override
        public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) throws TransactionException {
            return new DefaultTransactionStatus(
                    null, true, true,
                    transactionDefinition.isReadOnly(), true, null);
        }

        @Override
        public void commit(TransactionStatus transactionStatus) throws TransactionException {
            System.out.println("【commit】");
        }

        @Override
        public void rollback(TransactionStatus transactionStatus) throws TransactionException {
            System.out.println("【roll back】");
        }
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        context.register(TransatonalApplication.class);

        context.refresh();

        context.getBeansOfType(EchoService.class).forEach((beanName, bean) -> {
            System.out.println("BeanName：" + beanName + "，bean：" + bean);
            bean.echo();
        });

        context.close();
    }
}
